﻿Imports Heren.Common.Forms.Editor
Imports Heren.Common.Forms
Imports Heren.Common.ScriptEngine.Script
Imports Microsoft.VisualBasic
Imports System.Windows.Forms
Imports Heren.Common.Forms.Runtime
Imports System.Text
Imports Heren.Common.Libraries
Public Class 护士排班 : Inherits AbstractRuntimeHandler
    ''****************************************************************
    '' 这是护理电子病历表单后台运行支持脚本
    '' 注意：这是Visual Basic脚本，您可以不区分大小写 
    '' 请不要修改系统提供的方法名，以及方法名前面的Overrides关键字
    '' Script Language : Visual Basic
    '' Author : YangMingkun, Date : 2012-3-18
    '' Copyright (C) Heren Health Services (SUPCON) Co.,Ltd.
    ''****************************************************************

    Dim dtNurse As New DataTable '用于记录nurse列表
    Dim dtWard As New DataTable '用于记录病区列表
    Dim dtClass As New DataTable '用于记录班次列表
    Dim dtData As New DataTable '用于记录排班信息

    '表单脚本初始化
    Public Overrides Sub Initialize()
        Dim parent As Control = Me.FindControl("RootControl1")
        If (parent IsNot Nothing) Then
            parent.Dock = DockStyle.Fill
        End If

        InitialCombobox1()  '初始化病区下拉单 并选择默认病区
        InitialNurseData() '初始化人员信息 将人员信息绑定到dtNurse 并绑定到gdv的人员下拉框中
        InitialClassData() '初始化班次信息 将班次信息绑定到dtClass 并绑定到gdv的班次下拉框
        ShowWeekDay() '初始化时间
        BindData()

    End Sub


    '获取关键数据列表
    Public Overrides Function GetKeyDataList() As List(Of KeyData)
        Dim keyDataList As New List(Of KeyData)
        Return keyDataList
    End Function


    '更新表单中指定的数据
    Public Overrides Function UpdateFormData(ByVal param As String, ByVal data As Object) As Boolean
        Return True
    End Function


    '获取表单中指定的数据
    Public Overrides Function GetFormData(ByVal param As Object) As Object
        If param = "表单摘要" Then
            Return Me.GetFormSummary()
        End If
        Return Nothing
    End Function


    '获取表单摘要数据
    Public Function GetFormSummary() As String
        Dim control As Control = Me.FindControl("XTextBox1")
        If control IsNot Nothing Then
            Return control.Text
        End If
        Return String.Empty
    End Function

    '获取表单摘要数据
    Public Overrides Function SaveFormData(ByRef param As Object) As Boolean
        'showmessage(param.tostring)
        Me.SaveData()
        Return True
    End Function

    Public Sub SaveData()
        Dim xgdvlist As XDataGrid = Me.FindControl("xgdvList")
        Dim intLineNo As Integer = 0
        Dim strLineUserName As String = ""
        Dim strLineUserID As String = ""
        Dim IndexNo As String = ""

        Dim xcbo As XComboBox = Me.FindControl("XComboBox1")
        Dim xdtmonday As XDateTime = Me.FindControl("xdtMonday")

        '取消当前行焦点以便差错时聚焦错区
        'xgdvlist.currentcell.selected = false
        If CheckIndex(xcbo.SelectedValue, xdtmonday.Value, IndexNo) = True Then
            'showmessage("修改索引")
            UpdateIndex(IndexNo)
        Else
            'showmessage("新增索引")
            InsertIndex(xdtmonday.Value, IndexNo)
        End If
        Dim HasLineResouse As Boolean
        Dim strsqlarray As New List(Of String)

        Dim strMistake As String = ""

        '先遍历行  再遍历列 获得数据
        For i As Integer = 0 To xgdvlist.Rows.Count - 2
            HasLineResouse = False
            For j As Integer = 0 To xgdvlist.Rows(i).Cells.Count - 1
                Dim cell As DataGridViewCell = xgdvlist.Rows(i).Cells(j)
                If j = 0 Then
                    If cell.Value <> "" Then '在没选择需要排班的护士信息而选择了排班班次时的处理
                        strLineUserName = cell.Value
                        strLineUserID = dtNurse.Select("USER_NAME = '" + cell.Value.ToString + "'")(0)("USER_ID").ToString
                    Else
                        Exit For
                    End If
                Else
                    If cell.Value <> "" Then
                        HasLineResouse = True
                        If dtClass.Select("RANK_NAME = '" + cell.Value.ToString + "'").Length = 0 Then
                            strMistake = strMistake + "用户：" + strLineUserName + "，班次不可自编辑！" & vbCrLf
                            cell.Selected = True
                        Else
                            Dim strClassValue As String = dtClass.Select("RANK_NAME = '" + cell.Value.ToString + "'")(0)("RANK_CODE").ToString
                            Dim strsql As New StringBuilder
                            strsql.Append("insert into NUR_ROSTERING_DATA values")
                            strsql.AppendFormat("'" + strLineUserID + DateTime.Now.ToString("yyyyMMddHHmmss") + "','" + IndexNo.ToString + "','" + strLineUserID + "','" + strLineUserName + "',")
                            strsql.Append("'" + strClassValue + "',to_date('" + MyAddData(j - 1, xdtmonday.Value) + "','yyyy-mm-dd'),'" + intLineNo.ToString + "')")
                            strsqlarray.Add(strsql.ToString)
                        End If
                    End If
                End If
            Next
            If HasLineResouse = True Then
                intLineNo = intLineNo + 1
            End If
        Next
        If strMistake <> "" Then
            showmessage(strMistake)
            Return
        Else
            'showmessage("save")
            '清除所有的关于本周的记录
            DeleteIndexData(IndexNo)
            Dim sql() As String = strsqlarray.ToArray()
            Me.ExecuteUpdate(False, sql)
            showmessage("排班信息 保存成功！")
        End If
    End Sub

    '查询所有病区并初始化病区下拉列表  并选择默认病区
    Public Sub InitialCombobox1()
        Dim sql As New StringBuilder
        sql.Append("select dept_name,dept_code from dept_v ")
        sql.Append("where is_nurse=1 ")
        Dim ds As DataSet = Nothing
        Me.ExecuteQuery(sql.ToString, ds)
        dtWard = ds.Tables(0)
        Dim xcbo As XComboBox = Me.FindControl("XComboBox1")
        xcbo.DataSource = dtWard
        xcbo.DisplayMember = "dept_name"
        xcbo.ValueMember = "dept_code"
        '选择默认病区
        ChoiceDefaultWard()
    End Sub

    '选择病区列表
    Public Sub ChoiceDefaultWard()
        Dim strWardID As String = "" '0501
        Me.GetSystemContext("用户病区代码", strWardID)
        Dim xcbo As XComboBox = Me.FindControl("XComboBox1")
        xcbo.SelectedValue = strWardID
    End Sub

    '初始化人员， 绑定dtNurse 并初始化表格中的人员下拉框
    Public Sub InitialNurseData()
        Dim xcbo As XComboBox = Me.FindControl("XComboBox1")
        Dim sql As New StringBuilder
        sql.Append("select USER_ID,USER_NAME from USER_V where DEPT_CODE='" + xcbo.SelectedValue + "'")
        Dim ds As DataSet = Nothing
        Me.ExecuteQuery(sql.ToString, ds)
        dtNurse = ds.Tables(0)

        '绑定到人员下拉单
        BindNurseCbo()
    End Sub

    '绑定人员下拉单
    Public Sub BindNurseCbo()
        Dim xgdvlist As XDataGrid = Me.FindControl("xgdvList")
        Dim cbo As New Heren.Common.Controls.TableView.ComboBoxColumn
        cbo = xgdvlist.Columns(0)
        For i As Integer = 0 To dtNurse.Rows.Count - 1
            cbo.Items.Add(dtNurse.Rows(i)("USER_NAME"))
        Next i
    End Sub

    '一下注释  主要用于防止为更新的用户不存在NUR_SHIFT_RANK_DICT表 而采用字典表
    ''从字典中初始化班次table
    'public Sub InitialClassData()
    '    Dim sql As New StringBuilder
    '    sql.Append("select ITEM_CODE,ITEM_NAME from  ")
    '    sql.Append("where ITEM_TYPE='ROS_DATE' ")
    '    sql.Append("order by ITEM_NO")
    '    Dim ds As DataSet = Nothing
    '    Me.ExecuteQuery(sql.tostring,ds)
    '    dtClass = ds.tables(0)
    '    
    '    '绑定班次下拉列表
    '    BindClassCbo()
    'End Sub

    ''绑定班次下拉列表
    'public Sub BindClassCbo()
    '    Dim xgdvlist as XDataGrid  = Me.FindControl("xgdvList")
    '    Dim cbo As new Heren.Common.Controls.TableView.ComboBoxColumn
    '    For s As Integer=1 To xgdvlist.Columns.Count-1
    '        cbo = xgdvlist.Columns(s)
    '        for i as integer = 0 to dtClass.Rows.Count - 1
    '            cbo.items.add(dtClass.Rows(i)("ITEM_NAME"))
    '        next i
    '   Next s
    'End Sub

    ''将保存的信息保存到dtData中
    'public Sub GetRosData(Byval strndexno as string)
    '    Dim xdtmonday As XDateTime = Me.FindControl("xdtMonday")
    '    Dim xdtsunday As XDateTime = Me.FindControl("xdtSunday")
    '    Dim sql As New StringBuilder
    '    '根据行号对数据进行排序 有利于对数据进行还原
    '    sql.Append("select A.MANAGING_NURSE_NAME as ""护士名称"",B.ITEM_NAME as ""排班"",A.ROS_DATE as ""日期"",A.RECORD_LINE_NO as ""行号"",ROUND(TO_NUMBER(ROS_DATE - to_date('"+xdtmonday.value+"','yyyy-mm-dd hh24:mi:ss'))) as ""列号"" ")
    '    sql.Append("from NUR_ROSTERING_DATA A left join NUR_COMMON_DICT B on A.ROS_TYPE = B.ITEM_CODE AND B.ITEM_TYPE = 'ROS_DATE' ")
    '    sql.Append("where ROUND(TO_NUMBER(ROS_DATE - to_date('"+xdtmonday.value+"','yyyy-mm-dd hh24:mi:ss')))>=0 ")
    '    sql.Append("and ROUND(TO_NUMBER(ROS_DATE - to_date('"+xdtsunday.value+"','yyyy-mm-dd hh24:mi:ss')))<7 ")
    '    sql.Append("and ROS_NO ='"+strndexno+"'")
    '    sql.Append("order by to_number(""行号"")")
    '    Dim ds As DataSet = Nothing
    '    Me.ExecuteQuery(sql.tostring,ds)
    '    dtData = ds.tables(0)
    'End Sub

    '从字典中初始化班次table
    Public Sub InitialClassData()
        Dim xcbo As XComboBox = Me.FindControl("XComboBox1")
        Dim strSql As String = "select RANK_CODE,RANK_NAME from NUR_SHIFT_RANK_DICT where WARD_CODE='{0}'order by RANK_NO "
        Dim ds As DataSet = Nothing
        Me.ExecuteQuery(String.Format(strSql, xcbo.SelectedValue), ds)
        If ds.Tables(0).Rows.Count = 0 Then
            Me.ExecuteQuery(String.Format(strSql, "ALL"), ds)
        End If
        dtClass = ds.Tables(0)
        '绑定班次下拉列表
        BindClassCbo()
    End Sub

    '绑定班次下拉列表
    Public Sub BindClassCbo()
        Dim xgdvlist As XDataGrid = Me.FindControl("xgdvList")
        Dim cbo As New Heren.Common.Controls.TableView.ComboBoxColumn
        For s As Integer = 1 To xgdvlist.Columns.Count - 1
            cbo = xgdvlist.Columns(s)
            cbo.Items.Add("")
            For i As Integer = 0 To dtClass.Rows.Count - 1
                cbo.Items.Add(dtClass.Rows(i)("RANK_NAME"))
            Next i
        Next s
    End Sub

    '单击组件时发生。
    Private Sub btnThisweek_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim xgdvlist As XDataGrid = Me.FindControl("xgdvList")
        xgdvlist.Rows.Clear()
        ShowWeekDay()
        BindData()
        Me.IsModified = False
    End Sub

    '单击组件时发生。  显示上周时间
    Private Sub btnLastweek_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim xgdvlist As XDataGrid = Me.FindControl("xgdvList")
        xgdvlist.Rows.Clear()
        CountWeekDay(-1)
        BindData()
        Me.IsModified = False
    End Sub

    '单击组件时发生。显示下周时间
    Private Sub btnNextweek_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim xgdvlist As XDataGrid = Me.FindControl("xgdvList")
        xgdvlist.Rows.Clear()
        CountWeekDay(1)
        BindData()
        Me.IsModified = False
    End Sub

    '单击组件时发生。
    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'showmessage("baocun")
        Me.SaveData()
        Dim xgdvlist As XDataGrid = Me.FindControl("xgdvList")
        xgdvlist.Rows.Clear()
        BindData()
        Me.IsModified = False
    End Sub

    '新增到主索引表
    Public Sub InsertIndex(ByVal begintime As String, ByRef indexno As String)
        Dim strNurseCode As String = "LMBIN"
        'Me.GetSystemContext("用户编号", strNurseCode)
        Dim strNurseName As String = "林梅斌"
        'Me.GetSystemContext("用户姓名", strNurseName)
        Dim strDeptCode As String = "HL0501"
        'Me.GetSystemContext("用户科室代码", strDeptCode)
        Dim xcbo As XComboBox = Me.FindControl("XComboBox1")
        Dim strWardID As String = xcbo.SelectedValue
        Dim datetNow As String = DateTime.Now.ToString
        '主索引的no根据护士长的code+时间 进行绑定
        indexno = strNurseCode + datetNow
        Dim sql As New StringBuilder
        sql.Append("insert into NUR_ROSTERING_INDEX values ")
        sql.Append("('" + indexno + "','" + strNurseCode + "','" + strNurseName + "','" + strWardID + "',to_date('" + datetNow + "','yyyy-mm-dd hh24:mi:ss'),null,")
        sql.Append("to_date('" + begintime + "','yyyy-mm-dd hh24:mi:ss'),'" + strDeptCode + "')")
        Dim ds As DataSet = Nothing
        Me.ExecuteUpdate(False, sql.ToString)
    End Sub

    '更新主索引表
    Public Sub UpdateIndex(ByRef indexno As String)
        Dim dateTimeNow As DateTime = DateTime.Now
        Dim sql As New StringBuilder
        sql.Append("update NUR_ROSTERING_INDEX set ROS_MODIFY_TIME = to_date('" + dateTimeNow + "','yyyy-mm-dd hh24:mi:ss') ")
        sql.Append(" where ROS_NO = '" + indexno + "'")
        Me.ExecuteUpdate(False, sql.ToString)
    End Sub

    '删除所有的该星期的排版数据
    Public Sub DeleteIndexData(ByVal indexno As String)
        Dim sql As New StringBuilder
        sql.Append("delete from NUR_ROSTERING_DATA where ROS_NO = '" + indexno + "'")
        Me.ExecuteUpdate(False, sql.ToString)
    End Sub

    '单击组件时发生。
    Private Sub BtnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim xgdvlist As XDataGrid = Me.FindControl("xgdvList")
        xgdvlist.Rows.Clear()
        RefreshDataGrid()
    End Sub

    '单击组件时发生。
    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim xgdvlist As XDataGrid = Me.FindControl("xgdvList")
        '判断列表中是否有数据（主要为了防止该列表中没有选中行是的错误）
        If xgdvlist.Rows.Count <> 1 Then
            '判断当前行是否为最后一行
            If xgdvlist.CurrentRow.Index <> xgdvlist.Rows.Count - 1 Then
                xgdvlist.Rows.Remove(xgdvlist.CurrentRow)
            End If
        End If
    End Sub

    '初始化为本周时间
    Public Sub ShowWeekDay()
        CountWeekDay(0)
    End Sub

    '周次加减，根据两个时间控件的时间进行加减  
    Public Sub CountWeekDay(ByVal DIF As Integer)
        Dim xdtmonday As XDateTime = Me.FindControl("xdtMonday")
        Dim xdtsunday As XDateTime = Me.FindControl("xdtSunday")
        If DIF = 0 Then
            '获取当前时间
            Dim dtToday As DateTime = DateTime.Now
            '获取当前是周几  周日为1
            Dim count As Integer = Weekday(dtToday)
            '由于周日是属于上一周的 故需作判断，获取本周周一和周日
            If count = 1 Then
                xdtmonday.Value = MyAddData(DIF * 7 - 5 - count, dtToday)
                xdtsunday.Value = MyAddData(DIF * 7 + 1 - count, dtToday)
            Else
                xdtmonday.Value = MyAddData(DIF * 7 + 2 - count, dtToday)
                xdtsunday.Value = MyAddData(DIF * 7 + 8 - count, dtToday)
            End If
        Else
            xdtmonday.Value = MyAddData(DIF * 7, xdtmonday.Value)
            xdtsunday.Value = MyAddData(DIF * 7, xdtsunday.Value)
        End If
        '修改表格标题
        ChangeGDVHead()
    End Sub

    '设置表格标题
    Public Sub ChangeGDVHead()
        Dim xgdvlist As XDataGrid = Me.FindControl("xgdvList")
        Dim xdtmonday As XDateTime = Me.FindControl("xdtMonday")
        xgdvlist.Columns(0).HeaderText = "姓名"
        xgdvlist.Columns(1).HeaderText = "周一" & vbCrLf & MyAddData(0, xdtmonday.Value).ToString("yyyy-MM-dd")
        xgdvlist.Columns(2).HeaderText = "周二" & vbCrLf & MyAddData(1, xdtmonday.Value).ToString("yyyy-MM-dd")
        xgdvlist.Columns(3).HeaderText = "周三" & vbCrLf & MyAddData(2, xdtmonday.Value).ToString("yyyy-MM-dd")
        xgdvlist.Columns(4).HeaderText = "周四" & vbCrLf & MyAddData(3, xdtmonday.Value).ToString("yyyy-MM-dd")
        xgdvlist.Columns(5).HeaderText = "周五" & vbCrLf & MyAddData(4, xdtmonday.Value).ToString("yyyy-MM-dd")
        xgdvlist.Columns(6).HeaderText = "周六" & vbCrLf & MyAddData(5, xdtmonday.Value).ToString("yyyy-MM-dd")
        xgdvlist.Columns(7).HeaderText = "周日" & vbCrLf & MyAddData(6, xdtmonday.Value).ToString("yyyy-MM-dd")
        '刷新表格获取最新标题
        xgdvlist.Refresh()
    End Sub

    '时间加减
    Public Function MyAddData(ByVal count As Integer, ByVal datatime As DateTime) As DateTime
        Return DateAdd("d", count, datatime)
    End Function

    '判断该周信息是否已经被添加 判断是否需要初始化人员列表
    Public Sub BindData()
        Dim xcbo As XComboBox = Me.FindControl("XComboBox1")
        Dim xdtmonday As XDateTime = Me.FindControl("xdtMonday")
        'showmessage(xdtmonday.value.tostring)
        Dim strindexno As String = ""
        If CheckIndex(xcbo.SelectedValue, xdtmonday.Value, strindexno) = True Then
            'showmessage("indexno:"+strindexno)
            GetRosData(strindexno)
            ViewData()
        Else
            RefreshDataGrid()
        End If
    End Sub

    '将保存的信息保存到dtData中
    Public Sub GetRosData(ByVal strndexno As String)
        Dim xdtmonday As XDateTime = Me.FindControl("xdtMonday")
        Dim xdtsunday As XDateTime = Me.FindControl("xdtSunday")
        Dim sql As New StringBuilder
        '根据行号对数据进行排序 有利于对数据进行还原
        sql.Append("select A.MANAGING_NURSE_NAME as ""护士名称"",B.RANK_NAME as ""排班"",A.ROS_DATE as ""日期"",A.RECORD_LINE_NO as ""行号"",ROUND(TO_NUMBER(ROS_DATE - to_date('" + xdtmonday.Value + "','yyyy-mm-dd hh24:mi:ss'))) as ""列号"" ")
        sql.Append("from NUR_ROSTERING_DATA A left join NUR_SHIFT_RANK_DICT B on A.ROS_TYPE = B.RANK_CODE ")
        sql.Append("where ROUND(TO_NUMBER(ROS_DATE - to_date('" + xdtmonday.Value + "','yyyy-mm-dd hh24:mi:ss')))>=0 ")
        sql.Append("and ROUND(TO_NUMBER(ROS_DATE - to_date('" + xdtsunday.Value + "','yyyy-mm-dd hh24:mi:ss')))<7 ")
        sql.Append("and ROS_NO ='" + strndexno + "'")
        sql.Append("order by to_number(""行号"")")
        Dim ds As DataSet = Nothing
        Me.ExecuteQuery(sql.ToString, ds)
        dtData = ds.Tables(0)
    End Sub

    '已经添加的数据，显示在列表上
    Public Sub ViewData()
        Dim ALlineno As New ArrayList
        For Each dr As DataRow In dtData.Rows
            If ALlineno.Contains(dr("行号").ToString) = False Then
                ALlineno.Add(dr("行号").ToString)
                AddUserCell(CInt(dr("行号")), dr("护士名称"))
                AddClassCell(CInt(dr("行号")), CInt(dr("列号")), dr("排班"))
            Else
                AddClassCell(CInt(dr("行号")), CInt(dr("列号")), dr("排班"))
            End If
        Next
    End Sub

    '还原第一排护士信息
    Public Sub AddUserCell(ByVal x As Integer, ByVal cellvalue As String)
        Dim xgdvlist As XDataGrid = Me.FindControl("xgdvList")
        xgdvlist.Rows.Add()
        xgdvlist.Rows(x).Cells(0).Value = cellvalue
    End Sub

    '还原护士排班信息
    Public Sub AddClassCell(ByVal x As Integer, ByVal y As Integer, ByVal cellvalue As String)
        'showmessage("ROW:"+x.tostring+"COL:"+y.tostring)
        Dim xgdvlist As XDataGrid = Me.FindControl("xgdvList")
        xgdvlist.Rows(x).Cells(y + 1).Value = cellvalue
    End Sub

    '未添加的数据时 在列表上的显示人员列表
    Public Sub RefreshDataGrid()
        Dim count As Integer = 0
        For Each row As DataRow In dtNurse.Rows
            AddUserCell(count, row("USER_NAME"))
            count = count + 1
        Next
    End Sub

    '根据病区编号和开始时间 判断主索引中是否已存在该周的信息
    Public Function CheckIndex(ByVal code As String, ByVal begintime As String, ByRef indexno As String) As Boolean
        Dim sql As New StringBuilder
        sql.Append("select ROS_NO from NUR_ROSTERING_INDEX ")
        sql.Append("where ROUND(TO_NUMBER(to_date('" + begintime + "','yyyy-mm-dd hh24:mi:ss') - ROS_BEGIN_DATE))=0 ")
        sql.Append("and WARD_CODE ='" + code + "'")
        'showmessage(sql.tostring)
        Dim ds As DataSet = Nothing
        Me.ExecuteQuery(sql.ToString, ds)
        If ds.Tables(0).Rows.Count = 0 Then
            'showmessage("不存在该周信息")
            Return False
        Else
            'showmessage("存在该周信息")
            indexno = ds.Tables(0).Rows(0)(0).ToString
            Return True
        End If
    End Function


    '单击组件时发生。
    Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.RaiseCustomEvent(sender, "打印表单", False, "护士排班", Nothing)
    End Sub





End Class
